package com.linshidream.intrachat.simplenio.packet.handler;

import com.linshidream.intrachat.simplenio.packet.context.ConnectionContext;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Created on 2025/8/17 21:48
 *
 * @author linshidream
 * @version 1.0.0
 * @description
 */

public class ServerPacketHandler implements PacketHandler {

    @Override
    public void channelActive(ConnectionContext ctx) throws IOException {
        System.out.println("客户端已建立连接：" + ctx.channel().getRemoteAddress());
    }

    @Override
    public void channelRead(ConnectionContext ctx, String msg) throws IOException {

        // 下面就是业务处理，我这里简单的只是把消息再次返回，实际场景中根据业务自行开发
        try {
            System.out.println("服务端收到客户端消息:" + msg);

            String respMsg = "Echo:" + msg;
            ByteBuffer buffer = ctx.codec().encode(respMsg);
//            ctx.channel().write(buffer);

            // 采用写事件监听 ，并且需要在 worker 中开启写事件监听
            ctx.writer().send(buffer);

            System.out.println("服务端响应客户端消息:" + respMsg);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelInactive(ConnectionContext ctx) throws IOException {
        ctx.channel().close();
        System.out.println("客户端已关闭连接");
    }

    @Override
    public void exceptionCaught(ConnectionContext ctx, Throwable e) {
        try {
            System.out.println("客户端连接异常");
            e.printStackTrace();
            ctx.channel().close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
